package com.jingzhi.huimiao.fragment;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.jingzhi.huimiao.ChooseRoleActivity;
import com.jingzhi.huimiao.MainActivity;
import com.jingzhi.huimiao.R;
import com.jingzhi.huimiao.UploadActivity;
import com.jingzhi.huimiao.bean.RoleInfo;
import com.jingzhi.huimiao.mineActivity.PActivity;
import com.jingzhi.huimiao.mineActivity.ProgressActivity;
import com.jingzhi.huimiao.mineActivity.RankingActivity;
import com.jingzhi.huimiao.utils.CanstantUtils;
import com.jingzhi.huimiao.utils.DataStoreUtil;
import com.jingzhi.huimiao.utils.SQLdm;

/**
 * 我的界面
 * 
 * @author cxk
 * 
 */
public class MineFragment extends Fragment implements OnClickListener {

	private TextView title;
	private ImageView iv_mine_head;

	private RelativeLayout mine_ll1;
	private RelativeLayout mine_ll2;
	private RelativeLayout mine_ll3;
	private RelativeLayout mine_ll4;
	private RelativeLayout mine_ll5;
	private Long role;
	private SQLiteDatabase db;
	private Cursor rawQuery;
	private long word_id;
	private Cursor rightcur;
	private String responseData;

	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = View.inflate(getActivity(), R.layout.fragment_tab4, null);
		iv_mine_head = (ImageView) view.findViewById(R.id.iv_mine_head);
		mine_ll1 = (RelativeLayout) view.findViewById(R.id.mine_ll1);
		mine_ll2 = (RelativeLayout) view.findViewById(R.id.mine_ll2);
		mine_ll3 = (RelativeLayout) view.findViewById(R.id.mine_ll3);
		mine_ll4 = (RelativeLayout) view.findViewById(R.id.mine_ll4);
		addListener();

		 iv_mine_head.setOnClickListener(new View.OnClickListener() {
		
		 @Override
		 public void onClick(View v) {
		 // TODO Auto-generated method stub
		 getActivity().startActivity(new Intent(getActivity(),
		 UploadActivity.class));
		 // getActivity().finish();
		 }
		 });

		return view;
	}

	private void addListener() {
		// TODO Auto-generated method stub
		mine_ll1.setOnClickListener(this);
		mine_ll2.setOnClickListener(this);
		mine_ll3.setOnClickListener(this);
		mine_ll4.setOnClickListener(this);
	}

	@Override
	public void onDestroyView() {
		// TODO Auto-generated method stub
		super.onDestroyView();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.mine_ll1:// 我的排名
			startActivity(new Intent(getActivity(), RankingActivity.class));
//			getActivity().finish();
			break;
		case R.id.mine_ll2:// 我的进步曲线
			startActivity(new Intent(getActivity(), PActivity.class));
			
			break;
		case R.id.mine_ll3:// 我的生词本
			MainActivity a = (MainActivity)getActivity();
			a.setPage(1);
			break;
		case R.id.mine_ll4:// 切换角色
			// 与服务器传输当前角色信息
			sendRoleInfo();
			break;

		default:
			break;
		}
	}

	/**
	 * 与服务器传输角色信息 角色：进度，right表
	 */
	private void sendRoleInfo() {
		// TODO Auto-generated method stub
		// 用于捕获磁盘访问或者网络访问中与主进程之间交互产生的问题
		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
				.detectDiskReads().detectDiskWrites().detectNetwork()
				.penaltyLog().build());
		StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
				.detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
				.penaltyLog().penaltyDeath().build());

		// new Thread(){

		// 获取当前角色
		role = DataStoreUtil.getLong(getActivity(), "ChooseRole");

		try {
			// 创建用户信息类
			RoleInfo roleinfo = new RoleInfo();

			// 打开数据库输出流
			SQLdm s = new SQLdm();
			db = s.openDatabase(getActivity());

			// 将用户信息存放在Map中
			Map<String, String> roleInfo = new HashMap<String, String>();
			// roleInfo.put("role", vp_role.getCurrentItem() + 1 + "");
			roleinfo.role = role;

			Long uid = DataStoreUtil.getLong(getActivity(), "userid");
			// roleInfo.put("uid", uid + "");
			roleinfo.uid = uid;

			JSONObject ClientKey = new JSONObject();

			ClientKey.put("role", roleinfo.role);

			ClientKey.put("uid", roleinfo.uid);

			// 根据选择的角色去对应role表和right表查询进度
			if (role == 1) {
				// 查询单词进度
				rawQuery = db.rawQuery("select * from role1 where user_id="
						+ uid + ";", null);
				if (rawQuery.moveToFirst()) {
					word_id = rawQuery.getLong(rawQuery
							.getColumnIndex("word_id"));
				}

				ClientKey.put("word", word_id);

				// 查询正确率表
				rightcur = db.rawQuery("select * from right1 where user_id="
						+ uid + ";", null);

				// 创建一个争取率的jsonarray
				JSONArray RightKey = new JSONArray();

				while (rightcur.moveToNext()) {

					JSONObject RightInfo = new JSONObject();

					//
					long userId = rightcur.getLong(rightcur
							.getColumnIndex("user_id"));
					long taskId = rightcur.getLong(rightcur
							.getColumnIndex("task_id"));
					float rightLv = rightcur.getFloat(rightcur
							.getColumnIndex("right_lv"));
					Log.e("HEHE", "-----" + taskId + "-----" + rightLv);

					//
					RightInfo.put("userId", userId);
					RightInfo.put("taskId", taskId);
					RightInfo.put("rightLv", rightLv);

					RightKey.put(RightInfo);
				}

				ClientKey.put("right", RightKey);

			} else if (role == 2) {
				// 查询单词进度
				rawQuery = db.rawQuery("select * from role2 where user_id="
						+ uid + ";", null);
				if (rawQuery.moveToFirst()) {
					word_id = rawQuery.getLong(rawQuery
							.getColumnIndex("word_id"));
				}

				ClientKey.put("word", word_id);

				// 查询正确率表
				rightcur = db.rawQuery("select * from right2 where user_id="
						+ uid + ";", null);

				// 创建一个争取率的jsonarray
				JSONArray RightKey = new JSONArray();

				while (rightcur.moveToNext()) {

					JSONObject RightInfo = new JSONObject();

					//
					long userId = rightcur.getLong(rightcur
							.getColumnIndex("user_id"));
					long taskId = rightcur.getLong(rightcur
							.getColumnIndex("task_id"));
					float rightLv = rightcur.getFloat(rightcur
							.getColumnIndex("right_lv"));
					Log.e("HEHE", "-----" + taskId + "-----" + rightLv);

					//
					RightInfo.put("userId", userId);
					RightInfo.put("taskId", taskId);
					RightInfo.put("rightLv", rightLv);

					RightKey.put(RightInfo);
				}

				ClientKey.put("right", RightKey);
			} else {
				// 查询单词进度
				rawQuery = db.rawQuery("select * from role3 where user_id="
						+ uid + ";", null);
				if (rawQuery.moveToFirst()) {
					word_id = rawQuery.getLong(rawQuery
							.getColumnIndex("word_id"));
				}

				ClientKey.put("word", word_id);
				
				
				
				// 查询正确率表
				rightcur = db.rawQuery("select * from right3 where user_id="
						+ uid + ";", null);

				// 创建一个争取率的jsonarray
				JSONArray RightKey = new JSONArray();

				while (rightcur.moveToNext()) {

					JSONObject RightInfo = new JSONObject();

					//
					long userId = rightcur.getLong(rightcur
							.getColumnIndex("user_id"));
					long taskId = rightcur.getLong(rightcur
							.getColumnIndex("task_id"));
					float rightLv = rightcur.getFloat(rightcur
							.getColumnIndex("right_lv"));
					Log.e("HEHE", "-----" + taskId + "-----" + rightLv);

					//
					RightInfo.put("userId", userId);
					RightInfo.put("taskId", taskId);
					RightInfo.put("rightLv", rightLv);

					RightKey.put(RightInfo);
				}

				ClientKey.put("right", RightKey);
			}

			if (rightcur != null && !rightcur.isClosed()) {
				rightcur.close();
			}if(rawQuery != null){
				rawQuery.close();
			}

			// 将对象转化成json格式
			// String json = new Gson ().toJson(roleinfo);

			/* 封装Person对象 */

			JSONObject params = new JSONObject();

			params.put("Person", ClientKey);

			// 传输json数据
			/* 把JSON数据转换成String类型使用输出流向服务器写 */

			String content = String.valueOf(params);
			Log.e("CONTENT", content);

			URL url = new URL(CanstantUtils.choose_url);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();

			conn.setConnectTimeout(5000);

			conn.setDoOutput(true);// 设置允许输出

			conn.setRequestMethod("POST");

			conn.setRequestProperty("User-Agent", "Fiddler");

			conn.setRequestProperty("Content-Type", "application/json");

			// conn.setRequestProperty("Charset", utf-8);

			OutputStream os = conn.getOutputStream();

			os.write(content.getBytes());

			os.close();

			/* 服务器返回的响应码 */

			int code = conn.getResponseCode();

			if (code == 200)

			{

				BufferedReader in = new BufferedReader(new InputStreamReader(
						conn.getInputStream(), "UTF-8"));

				String retData = null;

				responseData = "";

				while ((retData = in.readLine()) != null)

				{

					responseData += retData;

				}

				Log.e("RESPONSEDATA", responseData);

				in.close();

				String retStr = responseData;
				Gson gson = new Gson();
				RoleInfo result = gson.fromJson(retStr, RoleInfo.class);
				if(null != result){
					if("error".equals(result.right)){
						Toast.makeText(getActivity(), "切换角色失败", Toast.LENGTH_SHORT)
						.show();

					}else{
						Toast.makeText(getActivity(), "切换角色成功", Toast.LENGTH_SHORT)
						.show();
						
						if(db!=null){
							db.close();
						}
						
						startActivity(new Intent(getActivity(),
								ChooseRoleActivity.class));
						getActivity().finish();
					}
				}else{
					Toast.makeText(getActivity(), "网络异常....", Toast.LENGTH_SHORT)
					.show();
				}
				
			}

			else

			{

				if(db!=null){
					db.close();
				}
				Toast.makeText(getActivity(), "网络异常....", Toast.LENGTH_SHORT)
						.show();

			}

			// 对接收到的服务器端的数据进行解析
			// String retStr = HttpUtils.sendPostRequest(
			// CanstantUtils.choose_url, roleInfo, "utf-8");
			// Log.e("TAG------", retStr);
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
}
